/**
 * 
 */
package org.spacegame;

import java.io.IOException;
import java.io.Serializable;
import java.net.InetAddress;

import org.spacegame.client.ClientCommunicator;
import org.spacegame.common.EntityState;
import org.spacegame.common.ObjectReceivedEvent;
import org.spacegame.common.ObjectReceivedListener;
import org.spacegame.server.Server;
import org.spacegame.server.ServerCommunicator;

/**
 * @author Vincent and Tom
 * 
 */
public class SpaceGame {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(final String[] args) throws IOException {
		int port = 1234;
		InetAddress address = null;

		for (int i = 0; i < args.length; i++) {
			final String arg = args[i];
			if ("-address".equals(arg)) {
				address = InetAddress.getByName(args[++i]);
			} else if ("-port".equals(arg)) {
				port = Integer.parseInt(args[++i]);
			} else {
				System.err.println("Usage: SpaceGame " + "[-address <hostname>] [-port <port number>]");
				System.exit(1);
			}
		}

		if (address == null) {
			address = InetAddress.getLocalHost();
			final ServerCommunicator serverCommunicator = new ServerCommunicator(port);
			serverCommunicator.start();
			synchronized (serverCommunicator) {
				while (true) {
					try {
						serverCommunicator.wait();
						break;
					} catch (final InterruptedException e) {
						// Do nothing.
					}
				}
			}
			final Server server = new Server(serverCommunicator);
			server.start();
		}

		final ClientCommunicator clientCommunicator = new ClientCommunicator(address, port);
		clientCommunicator.start();
		synchronized (clientCommunicator) {
			while (true) {
				try {
					clientCommunicator.wait();
					break;
				} catch (final InterruptedException e) {
					// Do nothing.
				}
			}
		}
		clientCommunicator.addObjectReceivedListener(new ObjectReceivedListener() {

			@Override
			public void objectReceived(final ObjectReceivedEvent event) {
				final Serializable object = event.getObject();
				if (object instanceof EntityState) {
					final EntityState serverState = (EntityState) object;
					System.out.println("Client peer: " + event.getRemoteAddress());
					System.out.println("Client received: " + serverState);
				}
			}
		});
		for (int i = 0; i < 10; i++) {
			final EntityState clientState = new EntityState(System.currentTimeMillis(), i, 0, 0, 0, 0);
			System.out.println("Client sending: " + clientState);
			try {
				clientCommunicator.send(clientState);
			} catch (final IOException e) {
				e.printStackTrace();
			}
			try {
				Thread.sleep(1000L);
			} catch (final InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.exit(0);
	}

}
